import Taro, { Component } from '@tarojs/taro'
import { View, Picker, Image } from '@tarojs/components'
import { DNavBar, DAtInpute, DLookImages } from '@/components'
import { AtInput, AtList, AtListItem, AtButton, AtActionSheet } from 'taro-ui'
import classNames from 'classnames'
import http from '@/api'
import './accountBook.scss'
import { validIdCard, validPhone, validUserName } from '@/utils/validate'
import dayjs from 'dayjs'
const conf = require('../../../config/conf')

export default class AccountBook extends Component {
  state = {
    title: '开通电子帐薄',
    showSheet: false,
    showLookImage: false,
    lookImageUrl: '',
    startTime: dayjs().format('YYYY-MM-DD'),

    roleActionActive: '企业用户',
    registerCardActive: '法定代表人',
    cardTypeActive: '身份证',
    accountTypeActive: '对公',
    isAuthActive: '是', // 是否授权给法人

    busFullNm: '', // 企业名称
    legalPerNm: '', // 法人真实姓名
    legalPerIdNo: '', // 法人证号
    agent: '', // 被授权人姓名
    agentIdNo: '', // 被授权人证件号
    agentIdEdt: '请选择截止日期', // 被授权人证件有效截止日期
    agentMbl: '',  // 被授权人手机号
    legalFrontPic: '', // 法人身份证正面
    legalBackPic: '', // 法人身份证反面
    bussLicenseID: '', // 营业执照

    // 企业角色
    roleAction: [
      {
        text: '个体工商户',
        type: 'roleActionActive',
        platRoleID: '002'
      },
      {
        text: '企业用户',
        type: 'roleActionActive',
        platRoleID: '100'
      },
    ],
    // 注册人身份
    registerCard: [
      {
        text: '法定代表人',
        type: 'registerCardActive',
        registrant: '1',
      },
      {
        text: '授权人',
        type: 'registerCardActive',
        registrant: '2'
      },
    ],
    // 法人证件类型
    cardType: [
      {
        text: '身份证',
        type: 'cardTypeActive',
        legalPerIdTyp: '01',
      },
      {
        text: '其他证件',
        type: 'cardTypeActive',
        legalPerIdTyp: '99'
      },
    ],
    isAuth: [
      {
        text: '是',
        type: 'isAuthActive',
      },
      {
        text: '否',
        type: 'isAuthActive',
      },
    ],
    // 账户类型
    accountType: [
      // {
      //   text: '对私',
      //   type: 'accountTypeActive',
      //   accType: 1
      // },
      {
        text: '对公',
        type: 'accountTypeActive',
        accType: 2
      },
    ],

    // 弹层显示内容（根据点击项动态渲染）
    sheetOptions: [],
    sheetTitle: '',
    sheetActive: ''
  }

  componentDidMount() {
    let { changeInfo } = this.$router.params
    if (changeInfo) {
      this.infoByEnterprise()
      return
    }
    this.getEntInfo()
  }

  async infoByEnterprise() {
    const accountInfo = await http.infoByEnterprise()
    this.getEntInfo()
    let {
      platRoleID,
      busFullNm,
      registrant,
      legalPerNm,
      accType,
      legalPerIdTyp,
      legalPerIdNo,
      agent,
      agentIdNo,
      agentIdEdt,
      agentMbl,
    } = accountInfo

    this.setState({
      roleActionActive: this.handlePlatRole(platRoleID),
      busFullNm,
      registerCardActive: registrant == '1' ? '法定代表人' : '授权人',
      legalPerNm,
      accountTypeActive: accType == '1' ? '对私' : '对公',
      cardTypeActive: legalPerIdTyp == '01' ? '身份证' : '其他证件',
      legalPerIdNo,
      agent,
      agentIdEdt: this.handleTime(agentIdEdt),
      agentIdNo,
      agentMbl,
    })
  }

  handleTime(time) {
    let timeStr = ''
    for (let index = 0; index < time.length; index++) {
      if (index == 4 || index == 6 || index == 8) {
        timeStr += '-'
      }
      timeStr += time[index]
    }
    return timeStr
  }

  async getEntInfo() {
    let {
      entName: busFullNm,
      entOwner: legalPerNm,
      fileList
    } = await http.getEntinfo()

    if (fileList.length) {
      fileList.forEach(item => {
        switch (item.cfType) {
          case '1': // 营业执照
            this.setState({
              bussLicenseID: item.cfFileUrl
            })
            break;
          case '2': // 法人身份证正面
            this.setState({
              legalFrontPic: item.cfFileUrl
            })
            break;
          case '3': // 法人身份证反面
            this.setState({
              legalBackPic: item.cfFileUrl
            })
            break;
          default:
            break;
        }
      })
      if (this.$router.params.changeInfo) return
    }

    this.setState({
      busFullNm,
      legalPerNm,
      agent: legalPerNm
    })
  }

  onTimeChange = (event) => {
    let timeArr = event.detail.value.split('-')
    timeArr = timeArr.map(item => {
      if (item.length == 1) {
        return '0' + item
      }
      return item
    })
    this.setState({
      agentIdEdt: timeArr.join('-')
    })
  }

  handlePlatRole(roleId) {
    // "存管企业角色:100:企业店铺、101：企业买家、、102:企业分公司买家、103:企业分公司卖家、002:个体工商户店铺、300:交易市场物流企业、310:交易市场仓储企业。"
    let roleObj = {
      '100': '企业用户',
      '101': '企业买家',
      '102': '企业分公司买家',
      '103': '企业分公司卖家',
      '002': '个体工商户',
      '300': '交易市场物流企业',
      '310': '交易市场仓储企业',
    };
    return roleObj[roleId];
  }

  // 点击弹层中的项
  onActive(active) {
    // type为需要改变的字段
    const { text, type } = active
    let { legalPerNm, legalPerIdNo } = this.state
    if (type == 'isAuthActive' && text == '是') {
      this.setState({
        agent: legalPerNm,
        agentIdNo: legalPerIdNo
      })
    } else if (type == 'isAuthActive' && text == '否') {
      this.setState({
        agent: '',
        agentIdNo: ''
      })
    }

    if (type == 'roleActionActive' && text == '企业用户') {
      this.setState({
        accountType: [
          {
            text: '对公',
            type: 'accountTypeActive',
            accType: 2
          },
        ],
        accountTypeActive: '对公'
      })
    } else {
      this.setState({
        accountType: [
          {
            text: '对私',
            type: 'accountTypeActive',
            accType: 1
          },
          {
            text: '对公',
            type: 'accountTypeActive',
            accType: 2
          },
        ],
      })
    }

    this.setState({
      [type]: text,
      showSheet: false
    })
  }

  onClose = () => {
    this.setState({
      showSheet: false,
      sheetOptions: []
    })
  }

  onRightHanlde(obj) {
    this.setState({
      showSheet: true,
      sheetOptions: obj.sheetOptions,
      sheetTitle: obj.sheetTitle,
      sheetActive: obj.sheetActive
    })
  }

  handleChange(type, newVal) {
    this.setState({
      [type]: newVal
    })
    if (type == 'legalPerIdNo' && this.state.isAuthActive == '是') {
      this.setState({
        agentIdNo: newVal
      })
    }
    if (type == 'legalPerNm' && this.state.isAuthActive == '是') {
      this.setState({
        agent: newVal
      })
    }
  }

  showToast(title) {
    Taro.showToast({
      title,
      icon: 'none'
    })
  }

  validate(data) {
    let { cardTypeActive } = this.state
    let valid = true
    let {
      busFullNm,
      legalPerNm,
      legalPerIdNo,
      agent,
      agentIdNo,
      agentMbl,
      agentIdEdt
    } = data
    if (!busFullNm) {
      this.showToast('企业名称不能为空')
      return valid = false
    }
    if (!legalPerNm) {
      this.showToast('法人真实姓名不能为空')
      return valid = false
    }
    if (!validUserName(legalPerNm)) {
      this.showToast('法人姓名格式错误')
      return valid = false
    }
    if (!legalPerIdNo) {
      this.showToast('法人证号不能为空')
      return valid = false
    }
    if (!agent) {
      this.showToast('被授权人姓名不能为空')
      return valid = false
    }
    if (!validUserName(agent)) {
      this.showToast('被授权人姓名格式错误')
      return valid = false
    }
    if (!agentIdNo) {
      this.showToast('被授权人证件号不能为空')
      return valid = false
    }

    if (cardTypeActive == '身份证') {
      if (!validIdCard(legalPerIdNo)) {
        this.showToast('法人身份证格式错误')
        return valid = false
      }
      if (!validIdCard(agentIdNo)) {
        this.showToast('被授权人证件号格式错误')
        return valid = false
      }
    }

    if (!agentIdEdt || agentIdEdt === '请选择截止日期') {
      this.showToast('被授权人证件有效截止日期不能为空')
      return valid = false
    }
    if (!agentMbl) {
      this.showToast('被授权人手机号不能为空')
      return valid = false
    }
    if (!validPhone(agentMbl)) {
      this.showToast('被授权人手机号格式错误')
      return valid = false
    }

    return valid
  }

  /**
   * 用图片换区龙存管对应的图片id
   * @param {string} fileUrl
   * @returns {stirng} id: 龙存管对应的图片id
   */
  async imgToLcgId(fileUrl) {
    const { rstCode, fileId } = await http.fileUpload({ fileType: '01', fileUrl, operType: '01' })
    if (rstCode == 0) {
      return fileId
    } else {
      Taro.showToast({
        title: '系统繁忙，请重新提交！',
        icon: 'none'
      })
      return false
    }
  }

  submit = async () => {
    const that = this
    /**
     * roleActionActive:        企业角色(platRoleID)
     * busFullNm:               企业名称
     * registerCardActive:      注册人身份(registrant)
     * legalPerNm:              法人真实姓名
     * cardTypeActive:          法定人证件类型(legalPerIdTyp)
     * legalPerIdNo:            法人证号
     * agent:                   被授权人姓名
     * agentIdNo                被授权人证件号
     * agentIdEdt               被授权人证件有效截止日期
     * agentMbl                 被授权人手机号
     * accountTypeActive:       账户类型(accType)
     * bussLicenseID            企业营业执照
     * legalFrontPic            法人身份证正面
     * legalBackPic             法人身份证反面
     * **/
    let {
      roleActionActive,
      registerCardActive,
      cardTypeActive,
      accountTypeActive,

      accountType,
      roleAction,
      registerCard,
      cardType,

      busFullNm,
      legalPerNm,
      legalPerIdNo,
      agent,
      agentMbl,
      agentIdNo,
      bussLicenseID,
      agentIdEdt,
      legalFrontPic,
      legalBackPic,
    } = this.state

    const accType = accountType.find(item => item.text === accountTypeActive).accType
    const platRoleID = roleAction.find(item => item.text === roleActionActive).platRoleID
    const registrant = registerCard.find(item => item.text === registerCardActive).registrant
    const legalPerIdTyp = cardType.find(item => item.text === cardTypeActive).legalPerIdTyp
    agentIdEdt = agentIdEdt.replace(/-/g, '')

    const electronicRegister = {
      platRoleID,
      busFullNm,
      registrant,
      legalPerNm,
      accType,
      legalPerIdTyp,
      legalPerIdNo,
      agent,
      agentIdNo,
      agentIdEdt,
      agentMbl,
      bussLicenseID,
      legalFrontPic,
      legalBackPic,
    }

    // 校验表单数据
    const valid = this.validate(electronicRegister)
    if (valid) {
      electronicRegister.bussLicenseID = await this.imgToLcgId(bussLicenseID)
      electronicRegister.legalFrontPic = await this.imgToLcgId(legalFrontPic)
      electronicRegister.legalBackPic = await this.imgToLcgId(legalBackPic)
      // 如果其中一个为false，则说明没有全部换成龙存管的id
      if (!electronicRegister.bussLicenseID || !electronicRegister.legalFrontPic || !electronicRegister.legalBackPic) return
      const { bodyData, infoData, signData } = await http.accountKaihu(electronicRegister)
      that.setState({
        bodyData, infoData, signData
      }, () => {
        that.refs.submit.click()
      })
    }
  }

  onLookHandle(lookImageUrl) {
    if (window.bridge) {
      let _images = [], i = 0
      _images.push(lookImageUrl)
      window.bridge.callHandler('previewPhoto', { "index": i, "images": _images }, function responseCallback() { })
    } else {
      this.setState({
        showLookImage: true,
        lookImageUrl
      })
    }
  }

  render() {
    const {
      title,
      agentIdEdt,
      bussLicenseID,

      roleAction,
      registerCard,
      cardType,
      accountType,
      isAuth,

      roleActionActive,
      registerCardActive,
      cardTypeActive,
      accountTypeActive,
      isAuthActive,

      showSheet,
      sheetOptions,
      sheetTitle,
      sheetActive,

      busFullNm,
      legalPerNm,
      legalPerIdNo,
      agent,
      agentIdNo,
      legalBackPic,
      legalFrontPic,
      agentMbl,

      infoData,
      bodyData,
      signData,

      lookImageUrl,
      showLookImage,
      startTime
    } = this.state

    return (
      <View className="b_accountbook">
        <DNavBar title={title}></DNavBar>

        <View className="b_accountbook_container">
          <DAtInpute title="企业角色" icon='chevron-right' require value={roleActionActive} onRightHanlde={this.onRightHanlde.bind(this, {
            sheetTitle: '企业角色',
            sheetOptions: roleAction,
            sheetActive: roleActionActive
          })}></DAtInpute>
          <AtInput title="企业名称" required value={busFullNm} onChange={this.handleChange.bind(this, 'busFullNm')}></AtInput>
          <DAtInpute title="注册人身份" icon='chevron-right' require value={registerCardActive} onRightHanlde={this.onRightHanlde.bind(this, {
            sheetTitle: '注册人身份',
            sheetOptions: registerCard,
            sheetActive: registerCardActive
          })}></DAtInpute>
          <AtInput title="法人真实姓名" maxLength={15} required value={legalPerNm} onChange={this.handleChange.bind(this, 'legalPerNm')}></AtInput>
          <DAtInpute title="法人证件类型" icon='chevron-right' require value={cardTypeActive} onRightHanlde={this.onRightHanlde.bind(this, {
            sheetTitle: '法人证件类型',
            sheetOptions: cardType,
            sheetActive: cardTypeActive
          })}></DAtInpute>
          <AtInput title="法人证件号" required maxLength={18} value={legalPerIdNo} placeholder="请输入法人证件号" onChange={this.handleChange.bind(this, 'legalPerIdNo')}></AtInput>
          <DAtInpute title="是否授权给法人" icon='chevron-right' require value={isAuthActive} onRightHanlde={this.onRightHanlde.bind(this, {
            sheetTitle: '是否授权给法人',
            sheetOptions: isAuth,
            sheetActive: isAuthActive
          })}></DAtInpute>
          <AtInput title="被授权人姓名" maxLength={15} required value={agent} placeholder="请输入被授权人姓名" onChange={this.handleChange.bind(this, 'agent')}></AtInput>
          <AtInput title="被授权人证件号" required maxLength={18} value={agentIdNo} placeholder="请输入被授权人证件号" onChange={this.handleChange.bind(this, 'agentIdNo')}></AtInput>
          <Picker mode='date' onChange={this.onTimeChange} start={startTime}>
            <AtList>
              <AtListItem title='被授权人证件有效截止日期' extraText={agentIdEdt} />
            </AtList>
          </Picker>
          <AtInput title="被授权人手机号" maxLength={11} required value={agentMbl} placeholder="请输入手机号" onChange={this.handleChange.bind(this, 'agentMbl')}></AtInput>
          <DAtInpute title="账户类型" icon='chevron-right' require value={accountTypeActive} onRightHanlde={this.onRightHanlde.bind(this, {
            sheetTitle: '账户类型',
            sheetOptions: accountType,
            sheetActive: accountTypeActive
          })}></DAtInpute>
          <DAtInpute title="企业营业执照"></DAtInpute>
          <View>
            <Image src={bussLicenseID} onClick={this.onLookHandle.bind(this, bussLicenseID)}></Image>
          </View>
          <DAtInpute title="法人身份证"></DAtInpute>
          <View className="legal_photo">
            <Image src={legalBackPic} onClick={this.onLookHandle.bind(this, legalBackPic)}></Image>
            <Image src={legalFrontPic} onClick={this.onLookHandle.bind(this, legalFrontPic)}></Image>
          </View>

          <AtButton className="submit" onClick={this.submit}>提交</AtButton>
        </View>

        {/* 弹出层面板 */}
        <AtActionSheet isOpened={showSheet} onClose={this.onClose}>
          <View className='b_enterpriseform__title'>
            <View className='b_enterpriseform__title_item'>{sheetTitle}</View>
          </View>
          <View className='b_enterpriseform__type'>
            {
              sheetOptions && sheetOptions.map((item, i) => {
                return <View
                  onClick={this.onActive.bind(this, item)}
                  className={classNames('b_enterpriseform__type_item', item.text === sheetActive ? 'b_enterpriseform__active' : '')}
                  key={i}
                >{item.text}</View>
              })
            }
          </View>
        </AtActionSheet>

        <DLookImages status={showLookImage} url={lookImageUrl} onLookHandle={() => { this.setState({ showLookImage: false }) }}></DLookImages>

        {/* 跳转龙存管页面 */}
        <form action={conf.fromURL} method="post">
          <input type="hidden" name="INFO" value={infoData} />
          <input type="hidden" name="CONTENTTYPE" value="json" />
          <input type="hidden" name="charset" value="GBK" />
          <input type="hidden" name="BODY" value={bodyData} />
          <input type="hidden" name="SIGN" value={signData} />
          <input type="submit" ref="submit" value="Submit" style={{ opacity: 0, width: 0, height: 0 }} />
        </form>
      </View>
    )
  }
}
